<?php
namespace User\Controller;
use Think\Controller;
class IndexController extends Controller {
    public function index() {
        echo C('encrypt_prefix');
    }

    public function register() {
    	$reg_info = I('post.');
    	$user_info = array(
    		'user_name' => $reg_info['user_name'],
    		'email'     => $reg_info['user_email'],
    		'password'  => $reg_info['user_password']
    	);
        //@TODO 加上信息检验
        $user_info['password'] = password_hash($user_info['password'], PASSWORD_DEFAULT);

    	$user = M('user');
    	$reg_res = $user->data($user_info)->add();

    	if ($reg_res) {
    		$res = array('status'=>'succ', 'redirect_url'=>U('User/Index/welcome'));
    		if(IS_AJAX) {
    			echo json_encode($res);
    		} else {
    			return $res;
    		}
    		
    	} else {
    		$res = array('status'=>'error', 'msg'=>'注册失败');
    		if(IS_AJAX) {
    			echo json_encode($res);
    		} else {
    			return $res;
    		}
    	}
    }

    public function welcome()
    {
    	echo "welcome to maoer";
    }

    //登录
    public function login()
    {
    	$user_pass  = I('post.user_pass', '');
    	$user_email = I('post.user_email', '');
        $res        = array(
            'status' => true, 
            'msg'=>'账号正确', 
            'redirect_url'=> U('Home/Index/discover')
        );

    	$user = M('user');
    	$user_info = $user->field('password, role_id, id, user_name')
                          ->where(array('email'=>$user_email))
                          ->find();
    	if (!$user_info) {
    		$res = array('status'=>false, 'msg'=>'无效的用户名或密码');
    	}
        
    	if( !password_verify($user_pass, $user_info['password'])) {
    		$res = array('status'=>false, 'msg'=>'用户名或密码错误');
    	}

        //将用户相关信息存入session中
        if ($res['status']) {
            $user_info['is_login'] = 1;
            unset($user_info['password']);
            session('user', $user_info);
        }
        
    	echo json_encode($res);
    }

    private function _check_reg_info(array $user_info) {
        $res = array('status'=>true, 'msg'=>'');
        if (!$user_info['user_name'] || !$user_info['user_email'] || !$user_info['user_password']) {
            $res = array('status'=> false, 'msg'=>'用户名或邮箱或者密码不能为空');
        }
    }
}